import com.jly.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class test {


    @Test
    public void test() throws IOException {


        SqlSession sqlSession = this.getSqlSession("sqlMapConfig.xml");
//        this.userList(sqlSession);
        this.addUser(sqlSession);
//        this.updateUser(sqlSession);
//        this.deleteUser(sqlSession);
    }

    /**
     *insert into tb_user values (#{id},#{username},#{password})
     * @param sqlSession
     */
    public void addUser(SqlSession sqlSession) {

        User user = new User();
        user.setId(4);
        user.setUsername("username4号");
        user.setPassword("123456");
        //执行sql
        int res = sqlSession.insert("UserMapper.add", user);
        System.out.println(res);
        //提交事务
//        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    /**
     *  update tb_user set username=#{username},password=#{password} where id=#{id}
     * @param sqlSession
     */
    public void updateUser(SqlSession sqlSession) {

        User user = new User();
        user.setId(4);
        user.setUsername("username4号修改");
        user.setPassword("123456");
        //执行sql
        int res = sqlSession.update("UserMapper.update", user);
        System.out.println(res);
        //提交事务
//        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    /**
     *delete from tb_user where id =#{id}
     * @param sqlSession
     */
    public void deleteUser(SqlSession sqlSession) {

        Integer id = 4;
        //执行sql
        int res = sqlSession.delete("UserMapper.delete", id);
        System.out.println(res);
        //提交事务
//        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    /**
     * select * from tb_user
     *
     * @param sqlSession
     */
    public void userList(SqlSession sqlSession) {
        //执行sql
        List<User> userList = sqlSession.selectList("UserMapper.findAll");
        System.out.println(userList);
        //释放资源
        sqlSession.close();
    }


    public SqlSession getSqlSession(String path) throws IOException {

        //加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream(path);
        //获得SqlSessionFactory工厂对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        //获得sqlSession对象 设置true则是自动提交不需要手动commit
//        SqlSession sqlSession = sqlSessionFactory.openSession();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession;
    }


}
